#!/bin/bash
# Usage: ./gitupdate.sh [-d <dir>] [-o <master>] <repo>

origin="master"

while getopts ":d:o:" opt; do
  case $opt in
    d) out_dir=$OPTARG ;;
    o) origin=$OPTARG ;;
    ?) echo "Usage: ./gitupdate.sh [-d <dir>] [-o <master>] <repo>"
       exit 2 ;;
  esac
done

if [[ $# -le 0 ]]; then
    echo "Error: repo url is required"
    exit 2
fi
repo=${!#}

[[ -n "$out_dir" ]] || out_dir=$(echo "$repo" | sed "s/.*\/\(.*\)\.git/\1/")

echo "repo=$repo"
echo "out_dir=$out_dir"
echo "origin=$origin"

if [[ -d "$out_dir" ]]; then
    cd "$out_dir" && git checkout "$origin" && git pull origin "$origin"
else
    git clone -b "$origin" "$repo" "$out_dir"
fi
